package com.example.demo.controller;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 全局统一返回结果类
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class ResponseData<T> {

    //返回码
    private Integer code;

    //返回消息
    private String msg;

    //返回数据
    private T data;

    // 返回数据
    protected static <T> ResponseData<T> build(T data) {
        ResponseData<T> result = new ResponseData<>();
        if (data != null) {
            result.setData(data);
        }
        return result;
    }

    public static <T> ResponseData<T> build(T body, Integer code, String message) {
        ResponseData<T> result = build(body);
        result.setCode(code);
        result.setMsg(message);
        return result;
    }

    public static <T> ResponseData<T> build(T body, ResultCodeEnum resultCodeEnum) {
        ResponseData<T> result = build(body);
        result.setCode(resultCodeEnum.getCode());
        result.setMsg(resultCodeEnum.getMessage());
        return result;
    }

    public static <T> ResponseData<T> ok() {
        return ResponseData.ok(null);
    }

    /**
     * 操作成功
     *
     * @param data baseCategory1List
     * @param <T>
     * @return
     */
    public static <T> ResponseData<T> ok(T data) {
        return build(data, ResultCodeEnum.SUCCESS);
    }

    public static <T> ResponseData<T> fail() {
        return ResponseData.fail(null);
    }

    /**
     * 操作失败
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> ResponseData<T> fail(T data) {
        return build(data, ResultCodeEnum.FAIL);
    }

    public ResponseData<T> message(String msg) {
        this.setMsg(msg);
        return this;
    }

    public ResponseData<T> code(Integer code) {
        this.setCode(code);
        return this;
    }
}
